package javaweblearn.session;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

public class IndexServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        //创建session
        req.getSession();
        out.write("本网站有如下书：<br/>");
        Set<Map.Entry<String, Books>> set = DB.getAll().entrySet();
                for(Map.Entry<String,Books> me : set){
                    Books book = me.getValue();
                    String url =req.getContextPath()+ "/servlet/BuyServlet?id=" + book.getId();
//                    req. encodeURL(java.lang.String url)用于对表单action和超链接的url地址进行重写
                    url = resp.encodeURL(url);//将超链接的url地址进行重写
                    out.print(book.getName());
                    out.println(book.getName()  + "   <a href='"+url+"'>购买</a><br/>");
                }
            }

            public void doPost(HttpServletRequest request, HttpServletResponse response)
                    throws ServletException, IOException {
                doGet(request, response);
            }
}

/**
 * @author javaweblearn
 * 模拟数据库
 */
        class DB{
            private static Map<String,Books> map = new LinkedHashMap<String,Books>();
            static{
                map.put("1", new Books("1","javaweb开发"));
                map.put("2", new Books("2","spring开发"));
                map.put("3", new Books("3","hibernate开发"));
                map.put("4", new Books("4","struts开发"));
                map.put("5", new Books("5","ajax开发"));
            }

            public static Map<String,Books> getAll(){
                return map;
            }
        }

class Books{

            private String id;
            private String name;

            public Books() {
                super();
            }
            public Books(String id, String name) {
                super();
                this.id = id;
                this.name = name;
            }
            public String getId() {
                return id;
            }
            public void setId(String id) {
                this.id = id;
            }
            public String getName() {
                return name;
            }
            public void setName(String name) {
                this.name = name;
            }
        }


